const jwt = require('jsonwebtoken');

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';
const JWT_REFRESH_EXPIRES_IN = process.env.JWT_REFRESH_EXPIRES_IN || '30d';

export interface JWTPayload {
  userId: string;
  username: string;
  role: string;
}

/**
 * 生成JWT令牌
 */
export function generateToken(payload: JWTPayload, expiresIn?: string): string {
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: expiresIn || JWT_EXPIRES_IN,
  });
}

/**
 * 生成带自定义过期时间的JWT令牌
 */
export function generateTokenWithExpiry(payload: JWTPayload, remember: boolean = false): string {
  const expiresIn = remember ? '3d' : '1d'; // 记住密码3天，否则1天
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn,
  });
}

/**
 * 验证JWT令牌
 */
export function verifyToken(token: string): JWTPayload | null {
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload;
    return decoded;
  } catch (error) {
    console.error('Token verification failed:', error);
    return null;
  }
}

/**
 * 生成刷新令牌
 */
export function generateRefreshToken(payload: JWTPayload): string {
  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: JWT_REFRESH_EXPIRES_IN,
  });
}

/**
 * 检查令牌是否即将过期（1小时内）
 */
export function isTokenExpiringSoon(token: string): boolean {
  try {
    const decoded = jwt.decode(token) as any;
    if (!decoded || !decoded.exp) return true;
    
    const expirationTime = decoded.exp * 1000; // 转换为毫秒
    const currentTime = Date.now();
    const oneHour = 60 * 60 * 1000; // 1小时的毫秒数
    
    return (expirationTime - currentTime) < oneHour;
  } catch {
    return true;
  }
}

/**
 * 从请求头中提取令牌
 */
export function extractTokenFromHeader(authHeader: string | undefined): string | null {
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null;
  }
  return authHeader.substring(7);
}

/**
 * 刷新令牌
 */
export function refreshToken(oldToken: string): string | null {
  const payload = verifyToken(oldToken);
  if (!payload) {
    return null;
  }
  
  // 创建新的payload，移除过期时间相关字段
  const newPayload: JWTPayload = {
    userId: payload.userId,
    username: payload.username,
    role: payload.role,
  };
  
  return generateToken(newPayload);
}